package com.example.fmgidsprototype.location;


import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.R.integer;
import android.R.string;
import android.support.v4.app.Fragment;

import com.example.fmgidsprototype.AppConstants;
import com.example.fmgidsprototype.DetailSliderActivity;
import com.example.fmgidsprototype.FmGidsPrototypeApp;
import com.example.fmgidsprototype.R;
import com.example.fmgidsprototype.R.id;
import com.example.fmgidsprototype.R.layout;
import com.example.fmgidsprototype.R.menu;
import com.example.fmgidsprototype.data.DataManager;
import com.example.fmgidsprototype.model.Venue;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class ShowMap extends Activity {
	private GoogleMap mMap;
	private FmGidsPrototypeApp app;
	private LatLng llVenue;
	private LatLng llLastknownlocation;

	private String[] markerids = new String[20];
	private long[] markervenueid= new long[20];
	
//	private int indexhelper;
	
	
	int indexhelper;
	// indexhelper;
	
	private float[] results=new float[5];
	private LocationManager LocationManager; //system service, which provides APIs to determine location and bearing of the underlying device (if available)
	private List<Marker> markers = new ArrayList<Marker>(); //the array is kept to find the boundries and change the view
	private Marker VenueMarker;
	
	
	public Marker MarkerMyLocation;
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_map);
		LocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
		
		String providerName;
		providerName = getLocationManager();
		
		// register for location updates
		LocationUpdateHandler LUH = new LocationUpdateHandler();
		LocationManager.requestLocationUpdates(providerName, 5000, 10, LUH);//provider,time,distance,listener

		/*
		 * The time it takes for your location listener to receive the first location fix is often 
		 * too long for users wait. Until a more accurate location is provided to your 
		 * location listener, you should utilize a cached location by calling getLastKnownLocation(String):
		 * */
		Location lastLoc = LocationManager.getLastKnownLocation(providerName);
		llLastknownlocation = new LatLng(lastLoc.getLatitude(), lastLoc.getLongitude());
		
		setUpMapIfNeeded();

        app = (FmGidsPrototypeApp)getApplication();
		DataManager dm = app.getDataManager();
		
		List<Venue> venues = dm.getAllVenuesWithLocations();

		
		
		indexhelper = 0;
		for (Venue v : venues) {
			llVenue = new LatLng(v.getLatitude(),v.getLongitude());
						
			//calculate the distance between the venue and My Location
			Location.distanceBetween(llLastknownlocation.latitude, llLastknownlocation.longitude, v.getLatitude(), v.getLongitude(), results);
			
			VenueMarker =mMap.addMarker(new MarkerOptions().position(llVenue).title(v.getName()  ).snippet("afstand: " + String.format(Locale.US, "%.2f",results[0]/1000) + " km"));
			
		//	Toast popup = Toast.makeText(getApplicationContext(), " i " + indexhelper, Toast.LENGTH_LONG);
		//	popup.show();
			
			markerids[indexhelper] = VenueMarker.getId();
			markervenueid[indexhelper] = v.getId();
			
			indexhelper = indexhelper + 1;
			markers.add(VenueMarker);
		}
		
		MarkerMyLocation = mMap.addMarker( new MarkerOptions().position(llLastknownlocation).title("Ik sta hier").snippet("Nauwkeurig to op "+ String.format(Locale.US, "%.2f",lastLoc.getAccuracy()) + " m" ) ) ;
		markers.add(MarkerMyLocation);
		
		//markers met id's mappen...
		mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
			
			@Override
			public void onInfoWindowClick(Marker marker) {
		//		Log.d("welk is mijn ID", marker.getId());
		//		Log.d("welk is mijn titel", marker.getTitle());
				
				int size = markerids.length;
			    for (int i=0; i<size; i++)
			    {
			    	
			    	if (marker.getId().equalsIgnoreCase(markerids[i])){
			    		Toast popup = Toast.makeText(getApplicationContext(), marker.getId() +  " = " + markerids[i]   , Toast.LENGTH_LONG);
						popup.show();	
						
					//	Intent intent = new Intent(getApplicationContext(), DetailSliderActivity.class);
					//	intent.putExtra(AppConstants.SELECTED_VENUE, selectedvenue );
					//	startActivity(intent);
			    	}
			    }	
			}
		});
	
		WrapCameraOverMarkers();
	}
	 
	
	private String getLocationManager(){
		Criteria provProps = new Criteria();
		provProps.setCostAllowed(false);
		provProps.setAccuracy(Criteria.ACCURACY_FINE);
		provProps.setPowerRequirement(Criteria.POWER_MEDIUM);

		// get a location provider with these criteria
		String providerName = LocationManager.getBestProvider(provProps, true);
		if (providerName == null || !LocationManager.isProviderEnabled(providerName)) {
			// if none is found use default
			providerName = LocationManager.NETWORK_PROVIDER;
		}
		
		if (!LocationManager.isProviderEnabled(providerName)) {
			String text = "No working location provider found!";
			Toast popup = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
			popup.show();
		}
		//providerName = LocationManager.GPS_PROVIDER;
		return providerName;
	}
	
	
/*	public void onInfoWindowClick(ShowMap showMap) {
		  Toast.makeText(getBaseContext(), 
		    "Info Window clicked@" + showMap.getId(), 
		    Toast.LENGTH_SHORT).show();
		 }
		 */
	private void WrapCameraOverMarkers(){
		LatLngBounds.Builder builder = new LatLngBounds.Builder();
		
		for  (Marker m : markers) {
		    builder.include(m.getPosition());
		}
		
		final LatLngBounds bounds = builder.build();
		final int padding = 10; // offset from edges of the map in pixels
		
		mMap.setOnCameraChangeListener(new OnCameraChangeListener() {

		    @Override
		    public void onCameraChange(CameraPosition arg0) {
		        // Move camera.
		        mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding));
		        // Remove listener to prevent position reset on camera move.
		        mMap.setOnCameraChangeListener(null);
		    }
		});
		
	}
	
	private void setUpMapIfNeeded() {
	    // Do a null check to confirm that we have not already instantiated the map.
	    if (mMap == null) {
	        mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
	                            .getMap();
	        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);  
	        mMap.setMyLocationEnabled(true);
	        // Check if we were successful in obtaining the map.
	        if (mMap != null) {
	            // The Map is verified. It is now safe to manipulate the map.
	        }
	    }
	}
	
	private class LocationUpdateHandler implements LocationListener {
		@Override
		public void onLocationChanged(Location location) {
			MarkerMyLocation.remove();
			LatLng llNewLocation = new LatLng(location.getLatitude(), location.getLongitude());
			MarkerMyLocation = mMap.addMarker( new MarkerOptions().position(llNewLocation).title("Ik sta hier").snippet("Nauwkeurig to op "+ String.format(Locale.US, "%.2f",location.getAccuracy()) + " m" ) ) ;
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.show_map, menu);
		
		return true;
	}

}
